package demo.modbus.dto;

import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by leohe on 2018/6/22.
 */
public class HoldingRegisterHandle {

    private final ConcurrentHashMap<Integer,HoldingRegister> holdingRegisterMap = new ConcurrentHashMap<>();
    private final Object lock = new Object();

    public HoldingRegister getByOffset(int offset){
        return holdingRegisterMap.containsKey(offset) ? holdingRegisterMap.get(offset) : null;
    }

    public HoldingRegister save(int offset, HoldingRegister holdingRegister){
        Assert.notNull(offset, "Offset must not be null");
        Assert.notNull(holdingRegister, "HoldingRegister must not be null");
        synchronized(this.lock) {
            //holdingRegisterMap.containsKey(offset) ? holdingRegisterMap.put(offset, holdingRegister) : holdingRegisterMap.replace(offset, holdingRegister);
            if (holdingRegisterMap.containsKey(offset)){
                holdingRegisterMap.replace(offset, holdingRegister);
            }else{
                holdingRegisterMap.put(offset, holdingRegister);
            }
        }
        return getByOffset(offset);
    }

    public List<HoldingRegister> getAll(){
        return new ArrayList(holdingRegisterMap.values());
    }
}
